<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\web\controller;

use app\common\model\User as UserModel;

class Auth extends Base
{
    /**
     * 登录页面
     */
    public function login()
    {
        // 如果已经登录，重定向到用户中心
        if ($this->user_id > 0) {
            return redirect('/user');
        }

        // 获取跳转地址
        $redirect = $this->request->get('redirect', '/');

        return $this->render('auth/login', [
            'title'    => '用户登录',
            'redirect' => $redirect
        ]);
    }

    /**
     * 注册页面
     */
    public function register()
    {
        // 如果已经登录，重定向到用户中心
        if ($this->user_id > 0) {
            return redirect('/user');
        }

        return $this->render('auth/register', [
            'title' => '用户注册',
        ]);
    }

    /**
     * 执行登录
     */
    public function doLogin()
    {
        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $username   = $this->request->post('username', '');
        $password   = $this->request->post('password', '');
        $captcha    = $this->request->post('captcha', '');
        $captchaKey = $this->request->post('captcha_key', '');
        $remember   = $this->request->post('remember', 0);

        if (empty($username) || empty($password)) {
            return $this->error('用户名和密码不能为空');
        }

        if (empty($captcha)) {
            return $this->error('请输入验证码');
        }

        if (empty($captchaKey)) {
            return $this->error('验证码已过期，请刷新');
        }

        // 验证图形验证码
        try {
            $captchaCheck = \Wangpeng1208\Captcha\Captcha::check($captcha, $captchaKey);
            if (!$captchaCheck) {
                return $this->error('验证码错误');
            }
        } catch (\Exception $e) {
            return $this->error('验证码验证失败');
        }

        try {
            // 查找用户 - 支持用户名或邮箱登录
            $user = UserModel::where(function ($query) use ($username) {
                $query->where('username', $username)->whereOr('email', $username);
            })->where('status', 1)->find();

            if (!$user) {
                return $this->error('用户不存在或已被禁用');
            }

            // 验证密码
            if (!password_verify($password, $user->password)) {
                return $this->error('密码错误');
            }

            // 设置Session - 使用Webman推荐方式
            $request = request();
            $session = $request->session();

            $session->set('user_id', $user->id);
            $session->set('username', $user->username);
            $session->set('email', $user->email);
            $session->set('login_time', time());

            // 设置Session过期时间
            if ($remember) {
                // 记住我：7天
                $session->set('expire_time', time() + 7 * 24 * 3600);
            } else {
                // 默认：24小时
                $session->set('expire_time', time() + 24 * 3600);
            }

            // 更新登录时间
            $user->last_login_time = time();
            $user->last_login_ip   = $this->request->getRealIp();
            $user->save();

            return $this->success('登录成功', [
                'redirect' => $this->request->post('redirect', '/user'),
                'user'     => [
                    'id'       => $user->id,
                    'username' => $user->username,
                    'email'    => $user->email,
                    'avatar'   => $user->avatar ?? '',
                    'is_vip'   => $user->is_vip ?? 0,
                    'points'   => $user->points ?? 0,
                    'level'    => $user->level ?? 1,
                ]
            ]);

        } catch (\Exception $e) {
            return $this->error('登录失败: ' . $e->getMessage());
        }
    }

    /**
     * 执行注册
     */
    public function doRegister()
    {
        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $username        = $this->request->post('username', '');
        $email           = $this->request->post('email', '');
        $password        = $this->request->post('password', '');
        $confirmPassword = $this->request->post('confirm_password', '');
        $agree           = $this->request->post('agree', 0);

        // 基本验证
        if (empty($username) || empty($email) || empty($password)) {
            return $this->error('用户名、邮箱和密码不能为空');
        }

        if ($password !== $confirmPassword) {
            return $this->error('两次输入的密码不一致');
        }

        if (!$agree) {
            return $this->error('请同意用户协议');
        }

        // 验证用户名格式
        if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
            return $this->error('用户名只能包含字母、数字和下划线，长度3-20位');
        }

        // 验证邮箱格式
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $this->error('邮箱格式不正确');
        }

        // 验证密码强度
        if (strlen($password) < 6) {
            return $this->error('密码长度不能少于6位');
        }

        try {
            // 检查用户名是否已存在
            $existUser = UserModel::where('username', $username)->find();
            if ($existUser) {
                return $this->error('用户名已存在');
            }

            // 检查邮箱是否已存在
            $existEmail = UserModel::where('email', $email)->find();
            if ($existEmail) {
                return $this->error('邮箱已被注册');
            }

            // 创建用户
            $user              = new UserModel();
            $user->username    = $username;
            $user->email       = $email;
            $user->password    = password_hash($password, PASSWORD_DEFAULT);
            $user->status      = 1;
            $user->create_time = time();
            $user->register_ip = $this->request->getRealIp();
            $user->save();

            return $this->success('注册成功，请登录', [
                'redirect' => '/user/login'
            ]);

        } catch (\Exception $e) {
            return $this->error('注册失败: ' . $e->getMessage());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        try {
            // 使用Webman推荐的session操作方式
            $request = request();
            $session = $request->session();

            // 清除所有session数据
            $session->flush();

        } catch (\Exception $e) {
            // 记录错误但不影响退出流程
            // error_log('Logout session error: ' . $e->getMessage());
        }

        // 添加响应头确保不缓存
        $response = redirect('/');
        $response->withHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
        $response->withHeader('Pragma', 'no-cache');
        $response->withHeader('Expires', '0');

        return $response;
    }

    /**
     * 忘记密码页面
     */
    public function forgot()
    {
        // 如果已经登录，重定向到用户中心
        if ($this->user_id > 0) {
            return redirect('/user');
        }

        return $this->render('auth/forgot', [
            'title' => '忘记密码',
        ]);
    }

    /**
     * 发送重置密码邮件
     */
    public function sendResetEmail()
    {
        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $email = $this->request->post('email', '');

        if (empty($email)) {
            return $this->error('邮箱不能为空');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $this->error('邮箱格式不正确');
        }
        try {
            // 查找用户
            $user = UserModel::where('email', $email)->where('status', 1)->find();
            if (!$user) {
                return $this->error('该邮箱未注册');
            }

            // 使用框架限流器：每个邮箱5分钟内只能发送1次重置邮件
            \Webman\RateLimiter\Limiter::check($email, 1, 300, '发送过于频繁，请5分钟后再试');

            // 生成重置token（24小时有效）
            $resetToken = md5($user->id . time() . rand(1000, 9999));
            \support\Cache::set('reset_token_' . $resetToken, [
                'user_id'     => $user->id,
                'email'       => $email,
                'expire_time' => time() + 24 * 3600
            ], 24 * 3600);

            // 生成重置链接
            $resetUrl = 'http://' . request()->host() . '/web/auth/resetPassword?token=' . $resetToken;

            // 邮件内容
            $emailContent = "
                <h2>密码重置</h2>
                <p>您好，" . ($user->username ?? '用户') . "！</p>
                <p>您请求重置密码，请点击下面的链接来重置您的密码：</p>
                <p><a href='{$resetUrl}' style='color: #007cff; text-decoration: none;'>{$resetUrl}</a></p>
                <p>此链接将在24小时后失效。</p>
                <p>如果您没有请求重置密码，请忽略此邮件。</p>
                <br>
                <p>此邮件由系统自动发送，请勿回复。</p>
            ";

            // 发送邮件
            (new \app\service\user\EmailMessageService())->send(
                $email,
                '密码重置 - ' . conf('site_name'),
                $emailContent
            );

            return $this->success('重置密码邮件已发送，请查收邮箱');

        } catch (\Webman\RateLimiter\RateLimitException $e) {
            // 限流异常
            return $this->error($e->getMessage());
        } catch (\Exception $e) {
            return $this->error('邮件发送失败，请稍后重试');
        }
    }



    /**
     * 重置密码页面
     */
    public function resetPassword()
    {
        $token = $this->request->get('token', '');

        if (empty($token)) {
            return $this->render('auth/reset_error', [
                'title'   => '重置密码',
                'message' => '重置链接无效'
            ]);
        }

        // 验证token
        $tokenData = \support\Cache::get('reset_token_' . $token);
        if (!$tokenData || $tokenData['expire_time'] < time()) {
            return $this->render('auth/reset_error', [
                'title'   => '重置密码',
                'message' => '重置链接已过期或无效'
            ]);
        }

        return $this->render('auth/reset_password', [
            'title' => '重置密码',
            'token' => $token,
            'email' => $tokenData['email']
        ]);
    }

    /**
     * 执行密码重置
     */
    public function doResetPassword()
    {
        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $token           = $this->request->post('token', '');
        $password        = $this->request->post('password', '');
        $confirmPassword = $this->request->post('confirm_password', '');

        if (empty($token) || empty($password) || empty($confirmPassword)) {
            return $this->error('参数不完整');
        }

        if ($password !== $confirmPassword) {
            return $this->error('两次输入的密码不一致');
        }

        if (strlen($password) < 6) {
            return $this->error('密码长度不能少于6位');
        }

        try {
            // 验证token
            $tokenData = \support\Cache::get('reset_token_' . $token);
            if (!$tokenData || $tokenData['expire_time'] < time()) {
                return $this->error('重置链接已过期或无效');
            }

            // 更新用户密码
            $user = UserModel::find($tokenData['user_id']);
            if (!$user) {
                return $this->error('用户不存在');
            }

            $user->password = password_hash($password, PASSWORD_DEFAULT);
            $user->save();

            // 删除token
            \support\Cache::delete('reset_token_' . $token);

            return $this->success('密码重置成功，请使用新密码登录', [
                'redirect' => '/user/login'
            ]);

        } catch (\Exception $e) {
            return $this->error('密码重置失败: ' . $e->getMessage());
        }
    }
}
